class EventBus {
  eventMap = new Map()
  constructor() {}
  static getInstance() {
    if(!EventBus.eb)
      EventBus.eb = new EventBus()
    return EventBus.eb
  }
  subscribe(name, cb) { // 事件订阅
    if(typeof cb !== 'function') return
    if(!this.eventMap.has(name))
      this.eventMap.set(name, [])
    const eventList = this.eventMap.get(name)
    !eventList.includes(cb) && eventList.push(cb)
    this.eventMap.set(name, eventList)
  }
  publish(name) { // 事件发布
    this.eventMap.get(name)?.forEach(cb => cb())
  }
  cancel(name, cb) { // 取消订阅
    if(this.eventMap.has(name)) {
      this.eventMap.set(name, this.eventMap.get(name).filter(i => i !== cb))
    }
  }
  clear(name) { // 清除订阅
    this.eventMap.delete(name)
  }
  clearAll() { // 清除所有订阅
    this.eventMap = new Map()
  }
}

export default EventBus.getInstance()